package com.example.chapter05;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.chapter05.bean.Person;
import com.example.chapter05.fragment.BlankFragment1;
import com.example.chapter05.fragment.BlankFragment3;
import com.example.chapter05.fragment.IFragmentCallback;
import com.example.chapter05.fragment.ItemFragment;

public class FragmentTestActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_test);
        findViewById(R.id.btn_change).setOnClickListener(this);
        findViewById(R.id.btn_change2).setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_change:
                // Activity 传递信息到 Fragment
                Bundle bundle = new Bundle();
                bundle.putParcelable("Person", new Person("Tom", 13));
                BlankFragment1 blankFragment1 = new BlankFragment1();
                blankFragment1.setArguments(bundle);
                replaceFragment(blankFragment1);
                break;
            case R.id.btn_change2:
                BlankFragment3 blankFragment3 = new BlankFragment3();
                blankFragment3.setFragmentCallback(new IFragmentCallback() {
                    @Override
                    public void sendMsgToActivity(String str) {
                        Toast.makeText(FragmentTestActivity.this, str, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public String getMsgFromActivity(String msg) {
                        return "Hello, I'm from Activity.";
                    }
                });

                replaceFragment(blankFragment3);
                break;
            default:
                break;
        }
    }

    // 动态切换fragment
    private void replaceFragment(Fragment fragment) {
        // 2. 获取FragmentManager，一般都是通过 getSupportFragmentManager()
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        // 3.开启一个事务transaction,一般调用fragmentManager的beginTransaction()
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        // 4.使用transaction进行fragment的替换
        // 创建replace事件，将fragment放置到fragment_layout中
        fragmentTransaction.replace(R.id.fragment_layout, fragment);
        fragmentTransaction.addToBackStack(null);
        // 5.提交事务
        fragmentTransaction.commit(); // 事务提交
    }
}